package com.ugoodtech.mdcc.web.controller;

import com.ugoodtech.mdcc.core.domain.Nation;
import com.ugoodtech.mdcc.core.domain.UserProfile;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import com.ugoodtech.mdcc.core.service.NationService;
import com.ugoodtech.mdcc.core.utils.AliServiceUtil;
import com.ugoodtech.mdcc.core.utils.ConverterUtils;
import com.ugoodtech.mdcc.web.common.BizConstants;
import com.ugoodtech.mdcc.web.common.CommonConstants;
import com.ugoodtech.mdcc.web.dto.ServerResponse;
import com.ugoodtech.mdcc.web.exception.BizException;
import com.ugoodtech.mdcc.web.pojo.vo.BrandOrientationVO;
import com.ugoodtech.mdcc.web.pojo.vo.ClientTypeVO;
import com.ugoodtech.mdcc.web.pojo.vo.PerformancePlanVO;
import com.ugoodtech.mdcc.web.pojo.vo.PerformanceReportRecordRequestVO;
import com.ugoodtech.mdcc.web.service.LocationService;
import com.ugoodtech.mdcc.web.service.PerformancePlanService;
import com.ugoodtech.mdcc.web.service.impl.PerformPlanHistoryRecord;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

/**
 * @author dean
 * @date 2020/6/17 14:01
 */
@RestController
@RequestMapping("/v1")
public class PerformancePlanController extends BaseController{

    @Autowired
    private PerformancePlanService performancePlanService;

    @Autowired
    private NationService nationService;

    @Autowired
    private PerformPlanHistoryRecord record;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Value("${oss.bucket.name}")
    private String ossBucketName;
    @Value("${oss.photo.bucket.name}")
    private String ossPhotoBucketName;
    /**
     * 解析业绩报告计划Excel文件
     */
    @RequestMapping(value = "/plan/excel", method = RequestMethod.POST)
    public ServerResponse resolvePlanExcel(@RequestParam MultipartFile file) {
        try {
            performancePlanService.resolvePlanExcel(file);
        } catch (BizException e) {
            e.printStackTrace();
            return ServerResponse.error("操作失败",e.getErrMsg());
        }
        return ServerResponse
                .success(ServerResponse.MSG_SUCCESS,true );
    }

    /**
     * 获取业绩报告可以查看的年份
     *
     * @return 年份列表
     */
    @RequestMapping(value = "/plan/years", method = RequestMethod.GET)
    public ServerResponse getYears() {
        isUserLogin();
        return ServerResponse.success(ServerResponse.MSG_SUCCESS, performancePlanService.getYears());
    }

    /**
     * 获取年度业绩报告
     */
    @RequestMapping(value = "/plan", method = RequestMethod.GET)
    public ServerResponse getPlan(@RequestParam String username, @RequestParam Integer year,
                                  @RequestParam String months,
                                  @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                                  @RequestParam(required = false, defaultValue = "1") Integer pageSize) {
        return ServerResponse.success(ServerResponse.MSG_SUCCESS, performancePlanService
                .getYearPlanPage(year, StringUtils.isEmpty(username) ? null : username,
                        StringUtils.isEmpty(months) ? null : stringToIntegerList(months, ","),
                        pageIndex, pageSize));
    }

    /**
     * 获取月度业绩报告
     */
    @RequestMapping(value = "/plan/month", method = RequestMethod.GET)
    public ServerResponse getMonthPlan(
            @RequestParam(required = false) String username, @RequestParam(required = false) Integer year,
            @RequestParam(required = false, defaultValue = "1,2,3,4,5,6,7,8,9,10,11,12") String months,
            @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
            @RequestParam(required = false, defaultValue = "2") Integer pageSize) {
        return ServerResponse.success(ServerResponse.MSG_SUCCESS, performancePlanService
                .getMonthPlanPage(year, StringUtils.isEmpty(username) ? null : username,
                        StringUtils.isEmpty(months) ? null : ConverterUtils.stringToIntegerList(months, ","),
                        pageIndex, pageSize));
    }

    /**
     * 获取业绩报告历史
     */
    @RequestMapping(value = "/plan/history", method = RequestMethod.GET)
    public ServerResponse listPlanHistory(@RequestParam Integer pageIndex,
                                          @RequestParam Integer pageSize, @RequestParam String username, @RequestParam String startTime,
                                          @RequestParam String endTime, @RequestParam Integer year)
            throws ParseException {
        Date startDate = StringUtils.isEmpty(startTime) ? null
                : DateUtils.parseDate(startTime, CommonConstants.DatePattern.SIMPLE_FORMAT);
        Date endDate = StringUtils.isEmpty(endTime) ? null
                : DateUtils.parseDate(endTime, CommonConstants.DatePattern.SIMPLE_FORMAT);
        if (endDate != null) {
            endDate = DateUtils.addDays(endDate, 1);
        }
        return ServerResponse.success(ServerResponse.MSG_SUCCESS,
                record.listPerformPlanRecordPage(pageIndex, pageSize,
                        PerformanceReportRecordRequestVO.builder().employeeName(username).startTime(startDate)
                                .endTime(endDate).year(year).build()));
    }

    /**
     * 获取业绩报告历史详情记录
     */
    @RequestMapping(value = "/plan/history/record", method = RequestMethod.GET)
    public ServerResponse getPlanHistoryRecord(@RequestParam Long id) {
        return ServerResponse.success(ServerResponse.MSG_SUCCESS, record.getReportOfSomeVersion(id));
    }

    /**
     * 下载excel模板
     * */
    @RequestMapping(value = "/plan/template", method = RequestMethod.GET)
    public void getFileTemplate(@RequestParam Integer year, HttpServletResponse response)
            throws IOException {
        if (log.isDebugEnabled()) {
            log.debug("Get performance plan excel template file.");
        }
        InputStream in = AliServiceUtil.getObject("template/performance_plan1593400778457.xlsx", ossBucketName);
//        ClassPathResource classPathResource = new ClassPathResource("销售人员业绩计划表.xlsx");
        String fileName = "销售人员业绩计划表.xlsx";
        Workbook workbook = new XSSFWorkbook(in);
        performancePlanService.changeYear(workbook, year);
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
        workbook.write(response.getOutputStream());
        response.getOutputStream().flush();
    }

    /**
     * 获取客户类型
     */
    @RequestMapping(value = "/search/clientType", method = RequestMethod.GET)
    public ServerResponse getClientType() {
        return ServerResponse.success(ServerResponse.MSG_SUCCESS, getClientTypes());
    }
    /**
     *  获取品牌定位
    * */
    @RequestMapping(value = "/user/brands", method = RequestMethod.GET)
    public ServerResponse listProvincesAndBrands() throws Exception {
        List<Nation> locationDOs = nationService.getLocationDOs("", BizConstants.Location.REPUBLIC_OF_PEOPLE_PARENT_ID * 1l, null);
        return ServerResponse.success(ServerResponse.MSG_SUCCESS, BrandOrientationVO.builder().brands(addBrand(locationDOs)).build());
    }

    ClientTypeVO getClientTypes() {
        return ClientTypeVO.builder().clientTypes(BizConstants.Question.RegularReport.CLIENT_TYPES).build();
    }
    private List<String> addBrand(List<Nation> locationDTOs) {
        List<String> provincesAndBrands = new ArrayList<>(locationDTOs.size() * 2);
        StringBuilder stringBuilder = new StringBuilder();
        String province;
        for (Nation locationDTO : locationDTOs) {
            stringBuilder.delete(0, stringBuilder.length());
            province = locationDTO.getProvince();
            provincesAndBrands.addAll(Arrays.asList(stringBuilder.append(province).append(BizConstants.Brand.WANG_DA)
                    .append(",").append(province).append(BizConstants.Brand.XIN_JIN).toString().split(",")));
        }
        return provincesAndBrands;
    }

    public static List<Integer> stringToIntegerList(String strings, String splitChar) {
        if (strings == null) {
            return null;
        }
        if (strings.length() == 0) {
            return new ArrayList<>(0);
        }
        if (splitChar == null) {
            splitChar = ",";
        }
        String[] stringArray = strings.split(splitChar);
        List<Integer> longList = new ArrayList<>(stringArray.length);
        for (String string : stringArray) {
            if (StringUtils.isNotEmpty(string)) {
                longList.add(Integer.valueOf(string));
            }
        }
        return longList;
    }
}
